package com.gitee_sunstar.idfa_helper

import android.content.Context
import android.util.Log
import com.bun.miitmdid.core.InfoCode
import com.bun.miitmdid.core.MdidSdkHelper
import com.bun.miitmdid.interfaces.IIdentifierListener
import com.bun.miitmdid.interfaces.IdSupplier
import com.bun.miitmdid.pojo.IdSupplierImpl
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader

class IdfaHelper private constructor() : IIdentifierListener {

    private val TAG = "IdfaHelper"

    private var listener: IdfaHelperListener? = null

    var isCertInit = false;

    companion object {
        val instance by lazy { IdfaHelper() }
    }

    fun bindListener(listener: IdfaHelperPlugin) {
        this.listener = listener
    }

    fun initIdfaHelper(context: Context, certFilePath: String, openLog: Boolean) {
        if (!isCertInit) {
            isCertInit = MdidSdkHelper.InitCert(context, loadPemFromAssetFile(context, certFilePath))
        }
        if (!isCertInit) {
            Log.w(TAG, "getDeviceIds: cert init failed")
            listener?.error("getDeviceIds: cert init failed")
        }
        // 调用SDK获取ID

        // 调用SDK获取ID
        val code = MdidSdkHelper.InitSdk(context, openLog, this)

        // 根据SDK返回的code进行不同处理
        val unsupportedIdSupplier = IdSupplierImpl()
        if (code == InfoCode.INIT_ERROR_CERT_ERROR) {                         // 证书未初始化或证书无效，SDK内部不会回调onSupport
            // APP自定义逻辑
            Log.w(TAG, "cert not init or check not pass")
            onSupport(unsupportedIdSupplier)
        } else if (code == InfoCode.INIT_ERROR_DEVICE_NOSUPPORT) {             // 不支持的设备, SDK内部不会回调onSupport
            // APP自定义逻辑
            Log.w(TAG, "device not supported")
            onSupport(unsupportedIdSupplier)
        } else if (code == InfoCode.INIT_ERROR_LOAD_CONFIGFILE) {            // 加载配置文件出错, SDK内部不会回调onSupport
            // APP自定义逻辑
            Log.w(TAG, "failed to load config file")
            onSupport(unsupportedIdSupplier)
        } else if (code == InfoCode.INIT_ERROR_MANUFACTURER_NOSUPPORT) {      // 不支持的设备厂商, SDK内部不会回调onSupport
            // APP自定义逻辑
            Log.w(TAG, "manufacturer not supported")
            onSupport(unsupportedIdSupplier)
        } else if (code == InfoCode.INIT_ERROR_SDK_CALL_ERROR) {             // sdk调用出错, SSDK内部不会回调onSupport
            // APP自定义逻辑
            Log.w(TAG, "sdk call error")
            onSupport(unsupportedIdSupplier)
        } else if (code == InfoCode.INIT_INFO_RESULT_DELAY) {             // 获取接口是异步的，SDK内部会回调onSupport
            Log.i(TAG, "result delay (async)")
        } else if (code == InfoCode.INIT_INFO_RESULT_OK) {                  // 获取接口是同步的，SDK内部会回调onSupport
            Log.i(TAG, "result ok (sync)")
        } else {
            // sdk版本高于DemoHelper代码版本可能出现的情况，无法确定是否调用onSupport
            // 不影响成功的OAID获取
            Log.w(TAG, "getDeviceIds: unknown code: $code")
        }

    }

    fun loadPemFromAssetFile(ctx: Context, assetFileName: String): String {
        return try {
            val `is`: InputStream = ctx.assets.open(assetFileName)
            val `in` = BufferedReader(InputStreamReader(`is`))
            val builder = StringBuilder()
            var line: String?
            while (`in`.readLine().also { line = it } != null) {
                builder.append(line)
                builder.append('\n')
            }
            builder.toString()
        } catch (e: IOException) {
            Log.e(TAG, "loadPemFromAssetFile failed")
            ""
        }
    }


    override fun onSupport(supplier: IdSupplier?) {
        if (supplier == null) {
            Log.w(TAG, "onSupport: supplier is null")
            return
        }
        if (listener == null) {
            Log.w(TAG, "onSupport: callbackListener is null")
            return
        }
        // 获取Id信息
        // 获取Id信息
        val isSupported: Boolean = supplier.isSupported
        val isLimited: Boolean = supplier.isLimited
        val oaid: String = supplier.oaid
        val vaid: String = supplier.vaid
        val aaid: String = supplier.aaid
        val idsText = """
            support: ${if (isSupported) "true" else "false"}
            limit: ${if (isLimited) "true" else "false"}
            OAID: $oaid
            VAID: $vaid
            AAID: $aaid
            
            """.trimIndent()
        Log.d(TAG, "onSupport: ids: \n$idsText")
        listener?.onIdsValid(idsText)
    }


    abstract class IdfaHelperListener {
        abstract fun onIdsValid(id: String)
        abstract fun error(msg: String)
    }
}